package com.infore.siteManagement.service.equipment.impl;

import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import com.infore.siteManagement.constant.Constants;
import com.infore.siteManagement.dao.IEntityManagerDao;
import com.infore.siteManagement.enums.ResultStatus;
import com.infore.siteManagement.repository.equipment.IEquipLogRepository;
import com.infore.siteManagement.service.equipment.IEquipLogService;
import com.infore.siteManagement.util.ArrayUtils;
import com.infore.siteManagement.util.Page;
import com.infore.siteManagement.util.PageObject;
import com.infore.siteManagement.util.ResultEntity;

@Service
public class EquipLogServiceImpl implements IEquipLogService{

	@Autowired
	private IEquipLogRepository iEquipLogRepository;
	@Autowired
	private IEntityManagerDao iEntityManagerDao;

	public ResultEntity query(String startTime, String endTime, String opcenId, String equipModelId,
			String userName,PageObject pageObject) {
		//拼接查询条件
		StringBuilder sb = new StringBuilder();
		if (StringUtils.isNotBlank(startTime) && StringUtils.isNotBlank(endTime)) {
			sb.append(" AND T.APPLY_TIME >= TO_DATE('"+startTime+"','yyyy-mm-dd hh24:mi:ss') "
					+ " AND T.APPLY_TIME <= TO_DATE('"+endTime+"','yyyy-mm-dd hh24:mi:ss')");
		}
		if (StringUtils.isNotBlank(equipModelId)) {
			sb.append(" AND T.EQUIP_MODEL_ID = "+equipModelId+" ");
		}
		if (StringUtils.isNotBlank(opcenId)) {
			sb.append(" AND T.OPCEN_ID = "+opcenId+" ");
		}
		if (StringUtils.isNotBlank(userName)) {
			sb.append(" AND T.USER_NAME LIKE '%"+userName+"%' ");
		}
		String sql = "SELECT T.ID,T.USER_NAME,T.ROLE_NAME,T.OPCEN_NAME,T.EQUIP_ID,T.EQUIP_MODEL_NAME,"
				+ "T.EQUIP_FACTORY_CODE,TO_CHAR(T.APPLY_TIME,'yyyy-mm-dd hh24:mi:ss') AS APPLY_TIME,"
				+ "T.REASON,T.PASSWORLD FROM EQUIP_LOG T WHERE 1=1 "+sb.toString()+" ";
		//判断分页
		if (pageObject != null && pageObject.getPageNumber() != null && pageObject.getPageSize() != null) {
			Page<Map<String, Object>> page = iEntityManagerDao.findPageBySQL(sql,pageObject.getPageNumber(),pageObject.getPageSize());
			return new ResultEntity(ResultStatus.SUCCESS,Constants.QUERY_SUCCESS).setPage(page);
		} else {
			List<Map<String, Object>> list = iEntityManagerDao.getListMapBySQL(sql);
			return new ResultEntity(ResultStatus.SUCCESS,Constants.QUERY_SUCCESS).setDataList(list);
		}
	}

	public ResultEntity delete(String id) {
		try {
			List<String> ids = ArrayUtils.stringToList(id);
			iEquipLogRepository.deleteByIdIn(ids);
			return new ResultEntity(ResultStatus.SUCCESS,Constants.DELETE_SUCCESS);
		} catch (Exception e) {
			return new ResultEntity(ResultStatus.SUCCESS,Constants.DELETE_FAILUE);
			//e.printStackTrace();
		}
	}
}
